package dbmrv1p0p1_admin

import (
	dbmrdb "github.com/ikaiguang/srv_admin/internal/migration/database"
	adminmodels "github.com/ikaiguang/srv_admin/internal/model/admin"
	tklog "github.com/ikaiguang/srv_toolkit/log"
	"github.com/pkg/errors"
)

// Admins .
type Admins struct{}

// Init
func (s *Admins) Init() (err error) {
	err = adminmodels.AdminsModel.InitWithDBConn(dbmrdb.DB())
	if err != nil {
		err = errors.WithStack(err)
		return
	}
	return
}

// CreateTable
func (s *Admins) CreateTable() (err error) {
	// table name
	tableName := adminmodels.AdminsModel.TableName()
	tklog.Info("数据库迁移：检查表：" + tableName)
	if dbmrdb.DB().Migrator().HasTable(tableName) {
		return
	}

	// 事务
	tx := dbmrdb.DB().Begin()
	defer func() {
		if err != nil {
			_ = tx.Rollback().Error
		}
	}()

	// 创建数据库
	tklog.Info("数据库迁移：创建表：" + tableName)
	err = tx.Exec(adminmodels.AdminsModel.TableSQL()).Error
	if err != nil {
		err = errors.WithStack(err)
		return
	}

	// 提交修改
	err = tx.Commit().Error
	if err != nil {
		err = errors.WithStack(err)
		return
	}
	return
}
